//
//  YLPaymentService.swift
//  YLPaymentDemo
//
//  Created by changhe on 2025/4/12.
//

import Foundation
import UIKit
import StoreKit

/// 支付服务管理类 - 单例模式
public class YLPaymentService {
    // MARK: - 单例
    
    /// 共享实例
    public static let shared = YLPaymentService()
    
    /// 支付管理器
    public private(set) var paymentManager: YLPaymentManager
    
    // MARK: - 初始化
    private init() {
        let converter = YLOrderIDConverterTool()
        // 创建支付配置
        let config = YLPaymentConfig(
            appId: "你的应用ID",        // 替换为实际的应用ID
            universalLink: "https://your.domain.com/path",  // 替换为实际的Universal Link
            urlScheme: "YLPaymentDemo", // 替换为应用的URL Scheme
            wxAppId: "你的微信AppID",    // 替换为实际的微信AppID
            wxUniversalLink: "https://your.domain.com/wechat", // 替换为微信指定的Universal Link
            alipayScheme: "YLPaymentDemo", // 替换为支付宝回调的URL Scheme
            iapVersion: .v2, // 使用StoreKit 2（iOS 15及以上）
            orderIdConverter: converter
        )
        
        // 使用配置初始化支付管理器
        paymentManager = YLPaymentManager(config: config)
        
    }
    
    // MARK: - 公共方法
    
    /// 初始化支付服务，应在App启动时调用
    public func setup() {
        debugPrint("YLPaymentService初始化完成")
        
        if paymentManager.isProcessorAvailable(for: .iap) {
            debugPrint("YLPaymentService 开始检查是否有未完成的订单")
            checkUnfinishedTransactions()
        }
    }
    
    /// 处理APP打开URL (用于支付宝、微信回调)
    public func handleOpenURL(_ url: URL) -> Bool {
        return paymentManager.handleOpenURL(url)
    }
    
    /// 处理Universal Link (用于微信Universal Link回调)
    public func handleOpenUniversalLink(_ url: URL) -> Bool {
        return paymentManager.handleOpenURL(url)
    }
    
    
    // MARK: - 私有方法
    
    /// 检查漏单和未完成交易
    private func checkUnfinishedTransactions() {
        
        paymentManager.checkUnfinishedTransactions { [weak self]transactionInfos in
            for transactionInfo in transactionInfos {
                print("[YLPaymentKit] 支付服务收到交易更新:")
                print("[YLPaymentKit] 交易ID: \(transactionInfo.transactionId)")
                print("[YLPaymentKit] 商品ID: \(transactionInfo.productId)")
                print("[YLPaymentKit] 交易状态: \(transactionInfo.state)")
                print("[YLPaymentKit] API版本: \(transactionInfo.apiVersion)")
                print("[YLPaymentKit] 订单ID: \(transactionInfo.orderId ?? "无")")
                print("[YLPaymentKit] 原始交易ID: \(transactionInfo.originalTransactionId ?? "无")")

                // 处理不同状态
                switch transactionInfo.state {
                case .purchased, .restored:
                    print("[YLPaymentKit] 交易已完成，开始验证购买")
                    // 交易完成，验证购买
                    self?.handleCompletedTransaction(transactionInfo)

                case .failed:
                    if let error = transactionInfo.error {
                        print("[YLPaymentKit] 交易失败: \(error.localizedDescription)")
                    } else {
                        print("[YLPaymentKit] 交易失败，但没有错误信息")
                    }

                case .purchasing:
                    print("[YLPaymentKit] 交易正在进行中")

                case .deferred:
                    print("[YLPaymentKit] 交易被延迟，等待外部操作")

                default:
                    print("[YLPaymentKit] 未知交易状态")
                    break
                }
            }
        }
    }
    
    func handleCompletedTransaction(_ transactionInfo: YLTransactionInfo) {
        
        paymentManager.verifyReceipt(using: YLValidatorTransaction(), transaction: transactionInfo) { result in
            
        }
    }
    
    /// 统一支付入口，支持所有支付类型
    /// - Parameters:
    ///   - paymentType: 支付类型
    ///   - params: 支付参数
    ///   - completion: 支付结果回调
    public func pay(paymentType: YLPaymentType, params: YLPaymentParams, validator: YLTransactionValidator? = nil, completion: @escaping (YLPaymentResult) -> Void) {
        // 创建支付模型并发起支付
        let model = YLPaymentModel(paymentType: paymentType, params: params)
        paymentManager.pay(model: model, validator: validator, completion: completion)
    }
    
    /// 内购支付便捷方法
    /// - Parameters:
    ///   - productId: 产品ID
    ///   - orderId: 订单ID
    ///   - completion: 支付结果回调
    public func payIAP(productId: String, orderId: String, validator: YLTransactionValidator, completion: @escaping (YLPaymentResult) -> Void) {
        let params = YLIAPParams(productId: productId, orderId: orderId)
        pay(paymentType: .iap, params: params, validator: validator, completion: completion)
    }
    
    /// 支付宝支付便捷方法
    /// - Parameters:
    ///   - orderId: 订单ID
    ///   - paymentString: 支付信息字符串
    ///   - completion: 支付结果回调
    public func payAlipay(orderId: String, paymentString: String, completion: @escaping (YLPaymentResult) -> Void) {
        let params = YLAlipayParams(orderId: orderId, paymentString: paymentString)
        pay(paymentType: .alipay, params: params, completion: completion)
    }
}
